package com.foreveross.proxyip.infra.impl;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.foreveross.proxyip.core.BaseCode;
import com.foreveross.proxyip.core.redis.PiRedisExecption;
import com.foreveross.proxyip.entity.RetrieveTmpEntity;
import com.foreveross.proxyip.infra.base.ddd.repository.EntityHibernateRepository;
import com.foreveross.proxyip.infra.base.ddd.repository.IBaseRepository;
import com.foreveross.proxyip.infra.base.ddd.repository.IJdbcRepository;
import com.foreveross.proxyip.infra.cache.BufferCacheManager;
import com.foreveross.proxyip.infra.cache.BufferInstance;
import com.foreveross.proxyip.infra.cache.Operations;
/**
 * (改用jdbc，实现完全,但还未使用)
 * @author lyq
 *
 */
@Service
public class RetrieveRepositoryImpl extends EntityHibernateRepository implements IBaseRepository {

	@Autowired
	IJdbcRepository jdbcRepository ;
	/*** 把在池中存在的记录移除到历史记录表  ***/
	private final static String INSERT_HISTORY_SQL 	 = "INSERT INTO PI_HISTORY  SELECT  FROM  PI_RETRIEVE T1 WHERE EXISTS (SELECT 1 FROM PI_RETRIEVE_TMP T2 WHERE T1.IP = T2.IP)";
	/*** 删除存在于池中的即时检索库记录  ***/
	private final static String DELETE_RETRIEVE_SQL  = "DELETE FROM PI_RETRIEVE  WHERE EXISTS (SELECT 1 FROM PI_RETRIEVE_TMP T2 WHERE PI_RETRIEVE.IP = T2.IP)";
	/*** 插入新记录 ***/
	private final static  String INSERT_RETRIEVE_SQL = "INSERT INTO PI_RETRIEVE SELECT * FROM PI_RETRIEVE_TMP";
	
	/**
	 * 保存数据
	 * @param list
	 * @return
	 * @throws PiRedisExecption 
	 * @throws NumberFormatException 
	 * @throws Exception
	 */
	public void transSaveList(List list) {
		Map <String,RetrieveTmpEntity> retrieveIps = new HashMap<String,RetrieveTmpEntity> ();
		for(Object obj:list){
			RetrieveTmpEntity retrieve = (RetrieveTmpEntity)obj;
			if(retrieveIps.containsKey(retrieve.getIp())){
				RetrieveTmpEntity old = retrieveIps.get(retrieve.getIp());
				try {
				if(old.getCreateTime()==null||old.getCreateTime().before(retrieve.getCreateTime())){
					retrieveIps.remove(retrieve.getIp());
					BufferInstance bufferinstance = new BufferInstance(old.toHistoryIpEntity(), Operations.CREATE);
					BufferCacheManager.getInstance(Integer.parseInt(BaseCode.getValue("TASKQUEUELOG_CACHEENTITYCOUNT"))).excure(bufferinstance,"history");
					retrieveIps.put(retrieve.getIp(), retrieve);
				}else if(retrieve.getCreateTime()==null||old.getCreateTime().after(retrieve.getCreateTime())){
					BufferInstance bufferinstance = new BufferInstance(old.toHistoryIpEntity(), Operations.CREATE);
					BufferCacheManager.getInstance(Integer.parseInt(BaseCode.getValue("TASKQUEUELOG_CACHEENTITYCOUNT"))).excure(bufferinstance,"history");
				}
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (PiRedisExecption e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				retrieveIps.put(retrieve.getIp(), retrieve);
			}
		}
		List<RetrieveTmpEntity> newList = new  ArrayList<RetrieveTmpEntity>(retrieveIps.values());
		Connection conn = null;
		boolean currAutoCommit = true;
		try{
			conn = jdbcRepository.getConnection();
			currAutoCommit = conn.getAutoCommit();
			conn.setAutoCommit(false);
			this.jdbcRepository.saveList(conn,newList, RetrieveTmpEntity.class);
			/*** 把在池中存在的记录移除到历史记录表  ***/
			this.jdbcRepository.execute(conn, INSERT_HISTORY_SQL);
			/*** 删除存在于池中的即时检索库记录  ***/
			this.jdbcRepository.execute(conn, DELETE_RETRIEVE_SQL);
			/*** 插入新记录 ***/
			this.jdbcRepository.execute(conn, INSERT_RETRIEVE_SQL);
			
			this.jdbcRepository.deleteAll(conn, RetrieveTmpEntity.class);
			conn.commit();
		}catch(Exception e){
			logger.info("存入数据出错:" + e);
		}finally{
			try {
				conn.setAutoCommit(currAutoCommit);
				conn.close();
			} catch (Exception e) {
				logger.info("存入数据出错:" + e);
			}
	}
	}
	
	
	
}
